/*
 * BooleanType.java
 *
 * Created on July 31, 2007, 7:50 PM
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.variable.types;

import tal.drivechain.matchers.BooleanMatcher;
import tal.drivechain.matchers.ValueMatcher;

/**
 * A DataType class that handles boolean values.
 * Name: "bool"
 * Value object: Boolean
 * Type code: 1
 * Syntax: bool:<true or false>
 * Can cast to Long or Integer.
 *
 * @author Tal Eisenberg
 */
public final class BooleanType extends DataType {
    
    /** Creates a new instance of BooleanType */
    public BooleanType() {
        super("bool", Boolean.class, 1);
    }

    public Object parseValue(String value) throws IllegalArgumentException {
        if (value.equals("true")) return Boolean.valueOf(true);
        else if (value.equals("false")) return Boolean.valueOf(false);
        else throw new IllegalArgumentException("Invalid bool value: " + value);        
    }

    @Override
    public Object cast(Object value) throws IllegalArgumentException {
        try {
            return super.cast(value);
        } catch (IllegalArgumentException ie) {
            int val;
            if (value instanceof Integer) val = (Integer)value;
            else if (value instanceof Long) val = ((Long)value).intValue();
            else if (value instanceof Float) val = ((Float)value).intValue();
            else if (value instanceof Double) val = ((Double)value).intValue();
            else throw new IllegalArgumentException("Can't cast value to bool: " + value);

            if (val==0) return false;
            else if (val==1) return true;
            else throw new IllegalArgumentException("Can't cast value to bool: " + val);
        }
    }

    @Override
    public ValueMatcher createValueMatcher() throws IllegalArgumentException {
        return new BooleanMatcher();
    }
    
}
